<template>
  <div class="min-h-screen p-6" style="background-color: #FAF9F5;">
    <!-- 页面头部 -->
    <div class="mb-6">
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <button
            @click="goBack"
            class="mr-4 p-2 text-gray-600 hover:text-gray-900 border border-gray-300 rounded-[0.6rem] hover:border-gray-400 transition-all duration-200 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
            </svg>
          </button>
          <div>
            <h1 class="text-2xl font-bold text-gray-900">通知公告</h1>
            <p class="mt-1 text-sm text-gray-600">查看学校发布的最新通知和公告信息</p>
          </div>
        </div>
        <div class="flex items-center gap-3">
          <button
            @click="refreshData"
            class="inline-flex items-center px-3 py-2 text-sm font-medium text-gray-700 border border-gray-300 rounded-[0.6rem] hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <ArrowPathIcon class="w-4 h-4 mr-2" />
            刷新
          </button>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="rounded-[0.6rem] border border-gray-200 mb-6 p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">搜索通知</label>
          <div class="relative">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索通知标题或内容..."
              class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
              style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
            />
            <MagnifyingGlassIcon class="absolute left-3 top-2.5 h-4 w-4 text-gray-400" />
          </div>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">通知类型</label>
          <select
            v-model="filters.type"
            class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <option value="">全部类型</option>
            <option value="urgent">紧急通知</option>
            <option value="academic">学术通知</option>
            <option value="activity">活动通知</option>
            <option value="system">系统通知</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">发布时间</label>
          <select
            v-model="filters.timeRange"
            class="w-full px-3 py-2 border border-gray-300 rounded-[0.6rem] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            <option value="">全部时间</option>
            <option value="today">今天</option>
            <option value="week">本周</option>
            <option value="month">本月</option>
          </select>
        </div>
        <div class="flex items-end">
          <button
            @click="resetFilters"
            class="w-full px-3 py-2 text-sm font-medium text-gray-700 border border-gray-300 rounded-[0.6rem] hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-all duration-200 active:scale-[0.985]"
            style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
          >
            重置筛选
          </button>
        </div>
      </div>
    </div>

    <!-- 通知列表 -->
    <div class="space-y-4">
      <div
        v-for="notice in filteredNotices"
        :key="notice.id"
        class="rounded-[0.6rem] border border-gray-200 hover:border-gray-300 transition-all duration-200 cursor-pointer active:scale-[0.985]"
        style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
        @click="openNotice(notice)"
      >
        <div class="p-6">
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <div class="flex items-center gap-3 mb-2">
                <span :class="[
                  'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
                  getTypeClass(notice.type)
                ]">
                  {{ getTypeText(notice.type) }}
                </span>
                <span v-if="notice.isTop" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                  <ExclamationTriangleIcon class="w-3 h-3 mr-1" />
                  置顶
                </span>
                <span v-if="!notice.isRead" class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                  未读
                </span>
              </div>
              <h3 class="text-lg font-medium text-gray-900 mb-2">{{ notice.title }}</h3>
              <p class="text-sm text-gray-600 mb-3 line-clamp-2">{{ notice.summary }}</p>
              <div class="flex items-center gap-4 text-sm text-gray-500">
                <div class="flex items-center">
                  <UserIcon class="w-4 h-4 mr-1" />
                  {{ notice.publisher }}
                </div>
                <div class="flex items-center">
                  <CalendarIcon class="w-4 h-4 mr-1" />
                  {{ formatDate(notice.publishTime) }}
                </div>
                <div class="flex items-center">
                  <EyeIcon class="w-4 h-4 mr-1" />
                  {{ notice.viewCount }} 次查看
                </div>
              </div>
            </div>
            <div class="ml-4">
              <ChevronRightIcon class="w-5 h-5 text-gray-400" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredNotices.length === 0" class="text-center py-12">
      <BellSlashIcon class="w-12 h-12 text-gray-400 mx-auto mb-4" />
      <h3 class="text-lg font-medium text-gray-900 mb-2">暂无通知</h3>
      <p class="text-gray-500">当前没有符合条件的通知公告</p>
    </div>

    <!-- 分页 -->
    <div v-if="filteredNotices.length > 0" class="mt-8 flex justify-center">
      <div class="flex items-center gap-2">
        <button
          @click="currentPage--"
          :disabled="currentPage === 1"
          class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          上一页
        </button>
        <span class="px-3 py-1 text-sm">{{ currentPage }} / {{ totalPages }}</span>
        <button
          @click="currentPage++"
          :disabled="currentPage === totalPages"
          class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 通知详情弹窗 -->
    <div v-if="showDetailModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-hidden">
        <div class="flex items-center justify-between p-6 border-b border-gray-200">
          <div class="flex items-center gap-3">
            <span :class="[
              'inline-flex items-center px-2 py-1 rounded-full text-xs font-medium',
              getTypeClass(selectedNotice?.type)
            ]">
              {{ getTypeText(selectedNotice?.type) }}
            </span>
            <h2 class="text-lg font-medium text-gray-900">{{ selectedNotice?.title }}</h2>
          </div>
          <button
            @click="closeDetailModal"
            class="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <XMarkIcon class="w-6 h-6" />
          </button>
        </div>
        <div class="p-6 overflow-y-auto max-h-[calc(90vh-120px)]">
          <div class="mb-6">
            <div class="flex items-center gap-4 text-sm text-gray-500 mb-4">
              <div class="flex items-center">
                <UserIcon class="w-4 h-4 mr-1" />
                发布者：{{ selectedNotice?.publisher }}
              </div>
              <div class="flex items-center">
                <CalendarIcon class="w-4 h-4 mr-1" />
                发布时间：{{ formatDateTime(selectedNotice?.publishTime) }}
              </div>
              <div class="flex items-center">
                <EyeIcon class="w-4 h-4 mr-1" />
                查看次数：{{ selectedNotice?.viewCount }}
              </div>
            </div>
          </div>
          <div class="prose max-w-none">
            <div v-html="selectedNotice?.content" class="text-gray-900 leading-relaxed"></div>
          </div>
          <div v-if="selectedNotice?.attachments?.length" class="mt-6">
            <h4 class="text-sm font-medium text-gray-900 mb-3">附件下载</h4>
            <div class="space-y-2">
              <div
                v-for="attachment in selectedNotice.attachments"
                :key="attachment.id"
                class="flex items-center justify-between p-3 border border-gray-200 rounded-lg"
              >
                <div class="flex items-center">
                  <DocumentIcon class="w-5 h-5 text-gray-400 mr-3" />
                  <div>
                    <p class="text-sm font-medium text-gray-900">{{ attachment.name }}</p>
                    <p class="text-xs text-gray-500">{{ attachment.size }}</p>
                  </div>
                </div>
                <button
                  @click="downloadAttachment(attachment)"
                  class="text-blue-600 hover:text-blue-900 text-sm font-medium transition-colors"
                >
                  下载
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '../../stores/app'
import {
  ArrowPathIcon,
  MagnifyingGlassIcon,
  UserIcon,
  CalendarIcon,
  EyeIcon,
  ChevronRightIcon,
  BellSlashIcon,
  XMarkIcon,
  ExclamationTriangleIcon,
  DocumentIcon
} from '@heroicons/vue/24/outline'

// 使用stores和router
const appStore = useAppStore()
const router = useRouter()

// 响应式数据
const notices = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const showDetailModal = ref(false)
const selectedNotice = ref(null)

const filters = ref({
  type: '',
  timeRange: ''
})

// 计算属性
const filteredNotices = computed(() => {
  let filtered = notices.value
  
  if (searchQuery.value) {
    const search = searchQuery.value.toLowerCase()
    filtered = filtered.filter(notice => 
      notice.title.toLowerCase().includes(search) ||
      notice.summary.toLowerCase().includes(search)
    )
  }
  
  if (filters.value.type) {
    filtered = filtered.filter(notice => notice.type === filters.value.type)
  }
  
  if (filters.value.timeRange) {
    const now = new Date()
    const filterDate = new Date()
    
    switch (filters.value.timeRange) {
      case 'today':
        filterDate.setHours(0, 0, 0, 0)
        break
      case 'week':
        filterDate.setDate(now.getDate() - 7)
        break
      case 'month':
        filterDate.setMonth(now.getMonth() - 1)
        break
    }
    
    filtered = filtered.filter(notice => new Date(notice.publishTime) >= filterDate)
  }
  
  // 按置顶和发布时间排序
  return filtered.sort((a, b) => {
    if (a.isTop && !b.isTop) return -1
    if (!a.isTop && b.isTop) return 1
    return new Date(b.publishTime) - new Date(a.publishTime)
  })
})

const totalPages = computed(() => {
  return Math.ceil(filteredNotices.value.length / pageSize.value)
})

// 方法
const loadNotices = async () => {
  // 模拟加载通知数据
  notices.value = [
    {
      id: 1,
      title: '关于2024年春季学期开学时间的通知',
      summary: '根据学校安排，2024年春季学期将于2月26日正式开学，请各位同学做好返校准备。',
      content: '<p>各位同学：</p><p>根据学校教学安排，现将2024年春季学期开学相关事宜通知如下：</p><p>1. 开学时间：2024年2月26日（周一）</p><p>2. 返校时间：2024年2月24日-25日</p><p>3. 请各位同学提前做好返校准备，按时到校报到。</p>',
      type: 'urgent',
      publisher: '教务处',
      publishTime: '2024-01-15T10:00:00',
      viewCount: 1250,
      isTop: true,
      isRead: false,
      attachments: [
        { id: 1, name: '开学通知详细安排.pdf', size: '2.5MB' }
      ]
    },
    {
      id: 2,
      title: '计算机学院学术讲座通知',
      summary: '邀请知名专家学者进行人工智能前沿技术讲座，欢迎广大师生参加。',
      content: '<p>各位师生：</p><p>计算机学院将举办学术讲座，具体安排如下：</p><p>主题：人工智能前沿技术与应用</p><p>时间：2024年1月20日 14:00-16:00</p><p>地点：学术报告厅</p>',
      type: 'academic',
      publisher: '计算机学院',
      publishTime: '2024-01-14T09:30:00',
      viewCount: 680,
      isTop: false,
      isRead: true,
      attachments: []
    },
    {
      id: 3,
      title: '学生社团招新活动开始啦！',
      summary: '各大学生社团开始招新，丰富多彩的社团活动等你来参加！',
      content: '<p>亲爱的同学们：</p><p>新学期各大学生社团开始招新活动，包括：</p><ul><li>计算机协会</li><li>摄影社</li><li>篮球社</li><li>文学社</li></ul><p>欢迎大家积极参与！</p>',
      type: 'activity',
      publisher: '学生处',
      publishTime: '2024-01-13T16:20:00',
      viewCount: 920,
      isTop: false,
      isRead: false,
      attachments: []
    },
    {
      id: 4,
      title: '系统维护通知',
      summary: '教务系统将于本周末进行维护升级，期间可能影响正常使用。',
      content: '<p>各位用户：</p><p>为了提升系统性能，教务系统将进行维护升级：</p><p>维护时间：2024年1月20日 22:00 - 2024年1月21日 06:00</p><p>维护期间系统暂停服务，请合理安排使用时间。</p>',
      type: 'system',
      publisher: '信息中心',
      publishTime: '2024-01-12T11:15:00',
      viewCount: 450,
      isTop: false,
      isRead: true,
      attachments: []
    }
  ]
}

const resetFilters = () => {
  filters.value = {
    type: '',
    timeRange: ''
  }
  searchQuery.value = ''
  currentPage.value = 1
}

const openNotice = (notice) => {
  selectedNotice.value = notice
  showDetailModal.value = true
  
  // 标记为已读
  if (!notice.isRead) {
    notice.isRead = true
    notice.viewCount++
  }
}

const closeDetailModal = () => {
  showDetailModal.value = false
  selectedNotice.value = null
}

const downloadAttachment = (attachment) => {
  // 模拟下载附件
  appStore.showNotification(`正在下载 ${attachment.name}`, 'info')
}

const getTypeClass = (type) => {
  const typeClasses = {
    'urgent': 'bg-red-100 text-red-800',
    'academic': 'bg-blue-100 text-blue-800',
    'activity': 'bg-green-100 text-green-800',
    'system': 'bg-yellow-100 text-yellow-800'
  }
  return typeClasses[type] || 'bg-gray-100 text-gray-800'
}

const getTypeText = (type) => {
  const typeTexts = {
    'urgent': '紧急通知',
    'academic': '学术通知',
    'activity': '活动通知',
    'system': '系统通知'
  }
  return typeTexts[type] || type
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const refreshData = async () => {
  try {
    await loadNotices()
    appStore.showNotification('数据刷新成功', 'success')
  } catch (error) {
    appStore.showNotification('刷新失败，请重试', 'error')
  }
}

// 返回首页
const goBack = () => {
  router.push('/student/home')
}

// 生命周期
onMounted(() => {
  loadNotices()
})
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.prose {
  max-width: none;
}

.prose p {
  margin-bottom: 1rem;
}

.prose ul {
  margin: 1rem 0;
  padding-left: 1.5rem;
}

.prose li {
  margin-bottom: 0.5rem;
}
</style>